package org.ualr.cpsc.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ualr.cpsc.server.PhotoService;

public class ImageUploadHandler extends HttpServlet {
    private static final long serialVersionUID = 1264570282519238586L;

    @Override
    protected void doPost(HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getName();
                if (name == null) {
                    continue;
                }
                if (!Arrays.asList("jpeg", "jpg", "bmp", "png", "gif").contains(PhotoService.getExtension(name))) {
                    continue;
                }
                InputStream stream = item.openStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int len;
                byte[] buffer = new byte[8192];
                while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, len);
                }
                String pub = req.getParameter("public");
                if (pub != null) pub = pub.trim();
                final boolean isPublic = pub != null && (
                        pub.equalsIgnoreCase("true") || pub.equalsIgnoreCase("t")
                                || pub.equals("1"));

                PhotoService.addPhoto(name, out.toByteArray(), isPublic);
            }
            resp.sendRedirect("/photos.jsp");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
